package cn.gzsxt.music.util;

import java.util.List;
import java.util.Map;

class LikeCondition{
	String keyword;
	List<String> likeElements;
	public LikeCondition(String keyword, List<String> likeElements) {
		super();
		this.keyword = keyword;
		this.likeElements = likeElements;
	}
}

class Limits{
	String beginIndex;
	String rows;
	public Limits(String beginIndex, String rows) {
		super();
		this.beginIndex = beginIndex;
		this.rows = rows;
	}
}

public class GetSqlUtil {
	
	private Map<String,String> tables = null; //key是表名, value是alias
	
	private Map<String,String> elements = null; //key是元素，value 是别名
	
	private List<String> conditions = null; //多表绑定条件 用and连接
	
	private LikeCondition like = null; //筛选条件like
	
	private Limits limit = null; //筛选条件limit

	public Map<String, String> getTables() {
		return tables;
	}

	public void setTables(Map<String, String> tables) {
		this.tables = tables;
	}

	public Map<String, String> getElements() {
		return elements;
	}

	public void setElements(Map<String, String> elements) {
		this.elements = elements;
	}

	public LikeCondition getLike() {
		return like;
	}

	public void setLike(String keyword, List<String> likeElements) {
		this.like = new LikeCondition(keyword,likeElements);
	}

	public Limits getLimit() {
		return limit;
	}

	public void setLimit(String beginIndex, String rows) {
		this.limit = new Limits(beginIndex,rows);
	}

	public List<String> getConditions() {
		return conditions;
	}

	public void setConditions(List<String> conditions) {
		this.conditions = conditions;
	}


	
	public String getMultipleSelectSql() {
		StringBuffer sql = new StringBuffer();
		sql.append("select ");
		if (this.elements == null) {
			sql.append("*");
		} else {
			for (String key : this.elements.keySet()) {
				sql.append(this.elements.get(key)+"."+key+" ,");
			}
		}
		sql.deleteCharAt(sql.length()-1);
		sql.append(" from ");
		if (this.tables == null) {
			sql.append("mc_song");
		} else {
			for (String key : this.tables.keySet()) {
				sql.append(key+" "+this.tables.get(key)+" ,");
			}
		}
		sql.deleteCharAt(sql.length()-1);
		if (this.conditions != null || this.like != null || this.limit != null) {
			sql.append(" where ");
			if (this.conditions != null) {
				for (String condition : this.conditions) {
					sql.append(condition+" and ");
				}
			}
			if (this.like != null) {
				for (String element : this.like.likeElements) {
					sql.append(element+" like '%"+this.like.keyword+"%' or ");
				}
				//删除最后一个" or "
				sql.delete(sql.length()-4, sql.length()-1);
			} else {
				//删除最后一个" and "
				sql.delete(sql.length()-5, sql.length()-1);
			}
			if (this.limit != null) {
				sql.append(" limit "+limit.beginIndex+","+limit.rows);
			}
		}		
		return sql.toString();
		
	}
}
